package com.hangoverstudios.batterysaver;
import java.lang.reflect.Method;
import java.security.Key;
import java.util.ArrayList;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.location.LocationManager;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.widget.Toast;



public class Utils {
	
	private static String algorithm = "AES";
	private static byte[] keyValue=new byte[] 
	{ 'A', 'S', 'e', 'Z', 'u', 'X', 'e', 'S', 'e', 'c', 'R', 'e', 't', 'K', 'e', 'f' };
	
	// Performs Encryption
    public static String encrypt(String plainText) throws Exception 
    {
        Key key = generateKey();
        Cipher chiper = Cipher.getInstance(algorithm);
        chiper.init(Cipher.ENCRYPT_MODE, key);
        byte[] encVal = chiper.doFinal(plainText.getBytes());
        String encryptedValue = Base64.encodeToString(encVal, 1983);
        return encryptedValue;
    }

    // Performs decryption
    public static String decrypt(String encryptedText) throws Exception 
    {
        // generate key 
        Key key = generateKey();
        Cipher chiper = Cipher.getInstance(algorithm);
        chiper.init(Cipher.DECRYPT_MODE, key);
        byte[] decordedValue = Base64.decode(encryptedText, 1983);
        byte[] decValue = chiper.doFinal(decordedValue);
        String decryptedValue = new String(decValue);
        return decryptedValue;//new String(Base64.decode(decryptedValue, Base64.DEFAULT));
    }

//generateKey() is used to generate a secret key for AES algorithm
    private static Key generateKey() throws Exception 
    {
        Key key = new SecretKeySpec(keyValue, algorithm);
        return key;
    }
    
    public static boolean isInternetPresent(Context context){
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivity != null)
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null)
                  for (int i = 0; i < info.length; i++)
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }
 
          }
          return false;
    }
    
    public static void setMobileDataEnabled(Context context, boolean enable)
    {
    	try
    	{	
    		ConnectivityManager dataManager;
	    	dataManager  = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
	    	Method dataMtd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
	    	dataMtd.setAccessible(true);
	    	dataMtd.invoke(dataManager, enable);
    	}
    	catch(Exception ex)
    	{
    		System.out.println("raj Error in enabling the MObile Data: "+ex);
    	}	    	 
    }
    public static void setWIFIEnabled(Context context, boolean enable)
    {
    	try
    	{
    		WifiManager wifiManager ;
			wifiManager  = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
			wifiManager.setWifiEnabled(enable);
    	}
    	catch(Exception ex)
    	{
    		System.out.println("raj Error in enabling the WIFI: "+ex);
    	}	    	
    }
    public static boolean isGPSEnabled(Context context)
    {
    	LocationManager mlocManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);;
        boolean enabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        return enabled;
    }
    
    public static void sendSMS(String phNumber, String msg)
    {    	
    	SmsManager sms = SmsManager.getDefault();
    	ArrayList<String> parts = sms.divideMessage(msg);
    	sms.sendMultipartTextMessage(phNumber, null, parts, null, null);    	
    }
    public static String getGoogleAccountName(Context context)
	 {
		 String accountName = null;
		 AccountManager manager = AccountManager.get(context); 
		 Account[] accounts = manager.getAccountsByType("com.google");
		 for (Account account : accounts) 
		 {
			 accountName = account.name;
			 System.out.println("raj Acounts: "+account.name);
		 }
		 return accountName;
	 }
    public static boolean isGmailValid(String email)
	{
		int index = email.indexOf("@");
		
		if(index != -1)
		{		
			if(email.substring(index+1, index+6).equals("gmail"))
			{
				if(email.length() > index+10 || email.length() < index+10)
					return false;
				else
				{
					if(email.substring(index+1, index+10).equals("gmail.com"))
						return true;
					else
						return false;
				}				
			}
			else
				return false;
		}
		else
			return false;			
	}
    public static boolean isEmailValid(String email)
	{	
		Pattern pattern;
		Matcher matcher;
		String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
		pattern = Pattern.compile(EMAIL_PATTERN);
		
		matcher = pattern.matcher(email);
		Boolean first_email = matcher.matches();
		
		if(first_email)
			return true;
		else
			return false;
	}
    public static String getsimSerialNumber(Context context)
    {
    	TelephonyManager mTelephonyMgr =
				(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);

				String sSimSerial = mTelephonyMgr.getSimSerialNumber();
				System.out.println("raj Phone serial number: "+sSimSerial);
				System.out.println("raj SIM Operator: "+mTelephonyMgr.getSimOperatorName().toString());
    	return sSimSerial;
    }
    public static String getCountryName(Context context)
    {
    	TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        String countryCode = tm.getSimCountryIso();
        Locale loc = new Locale("",countryCode);
        return loc.getDisplayCountry().toString();
    }
    public static boolean isFrontCameraPresent() 
    {
        
        int numberOfCameras = Camera.getNumberOfCameras();
        for (int i = 0; i < numberOfCameras; i++)
        {
          CameraInfo info = new CameraInfo();
          Camera.getCameraInfo(i, info);
          if (info.facing == CameraInfo.CAMERA_FACING_FRONT) 
          {
        	  return true;
          }
        }
        return false;
    }
    
    public static int getScreenWidth(Context context)
    {
    	DisplayMetrics displaymetrics = context.getResources().getDisplayMetrics();
    	return displaymetrics.widthPixels;
    }
    public static int getScreenHeight(Context context)
    {
    	DisplayMetrics displaymetrics = context.getResources().getDisplayMetrics();
    	return displaymetrics.heightPixels;
    }
    
    public static boolean isWifiEnabled(Context context) {
        boolean result = false;
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        android.net.NetworkInfo activeNetwork = connectivityManager
                .getActiveNetworkInfo();
        if (activeNetwork != null
                && (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)) {
                result = true;
                activeNetwork.getDetailedState();
            } else {
            	 result = false;
            }
        
        return result;
    }
    
	public static void setgps(Context context)
	{	
		Intent gps = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);	
		gps.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(gps);
	}
	
	
	public static boolean isMobileDataEnabled(Context context) 
    {
        boolean result = false;
        ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
           
        	if(activeNetwork.isConnectedOrConnecting())
	        {
	            result = true;
	        }
	        else 
	        {
	           	result = false;
	        }
        	 System.out.println("raj data enabled: "+result);
             
             return result; 
    }
	
	public static int getDeviceAndroidVersion(Context context)
	{
		return android.os.Build.VERSION.SDK_INT;
	}
	
	public static boolean isDeviceInSilentMode(Context context)
	{
		AudioManager mobilemode;
		mobilemode = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
		return (mobilemode.getRingerMode() == AudioManager.RINGER_MODE_SILENT);
	}
	public static boolean isDeviceInVibrateMode(Context context)
	{
		AudioManager mobilemode;
		mobilemode = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
		return (mobilemode.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE);
	}
	
	public static int getRingerMode(Context context)
	{
		AudioManager am = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
		return am.getRingerMode();
		
	}
	
	public static void setDeviceMode(Context context, int mode)
	{
		AudioManager mobilemode;
		mobilemode = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
		mobilemode.setRingerMode(mode);
	}
	public static boolean isBluetoothEnabled() 
    {
    	BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        return bluetoothAdapter.isEnabled();
    }
	public static void setBluetoothEnabled(boolean enable)
    {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(enable)
        	bluetoothAdapter.enable();
        else
        	bluetoothAdapter.disable();
    }
	public static void autoRotation(Context context)
	{
		if(android.provider.Settings.System.getInt(context.getContentResolver(),Settings.System.ACCELEROMETER_ROTATION, 0) == 1)
	    {
		    android.provider.Settings.System.putInt(context.getContentResolver(),Settings.System.ACCELEROMETER_ROTATION, 0);
		    Toast.makeText(context, "Rotation OFF", Toast.LENGTH_SHORT).show();
	    }
	    else
	    {
		    android.provider.Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 1);
		    Toast.makeText(context, "Rotation ON", Toast.LENGTH_SHORT).show();
	    }
	}
	
	
}
